package cn.wdm.org.service.impl;

import cn.wdm.basic.service.impl.BaseServiceImpl;
import cn.wdm.basic.util.PageList;
import cn.wdm.org.domain.Department;
import cn.wdm.org.mapper.DepartmentMapper;
import cn.wdm.org.query.DepartmentQuery;
import cn.wdm.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    @Transactional
    public void save(Department department) {
        departmentMapper.save(department);
        this.update(department);
    }

    @Override
    @Transactional
    public void update(Department department) {
        //有了自增的id
        //两种情况，有上级部门，和没有上级部门，没有上级部门，dirpath就是他自己/id。
        //有上级部门 就是他上级部门的dirpath路径，加上自增id
        if (department.getDepartmentParent()==null){
            department.setDirPath("/"+department.getId());
        }else{
            //有上级的部门
            //拿到上级部门
            Department parent = departmentMapper.loadById(department.getDepartmentParent().getId());
            String dirpath = parent.getDirPath() + "/" + department.getId();
            department.setDirPath(dirpath);
        }
        departmentMapper.update(department);
    }

    @Override
    public List<Department> deptTree() {
        //查询全部
        List<Department> departments = departmentMapper.loadAll();
        //建立map集合
        HashMap<Long, Department> treeMap = new HashMap<Long, Department>();
        //将每次遍历的值给map集合，key是id，valule是自己
        for (Department department : departments) {
            treeMap.put(department.getId(),department);
        }
        //查找祖宗部门
        ArrayList<Department> firstDepts = new ArrayList<>();
        //遍历查找自己上一级，如果没有上一级就是祖宗，将其放入到指定的集合里面
        //如果有上一级，就将自己放到，爹的department的children集合里面
        for (Department department : departments) {
            //当前对象没有上级的id，就是祖宗，放到祖宗集合里面
            if (department.getParent_id()==null){
                firstDepts.add(department);
            }else{
                //有上级的id，将上级的部门查到，将自己放到上级部门的children中
                //这是上级部门
                Department parentDept = treeMap.get(department.getParent_id());
                //将自己放到上级部门的children中
                if(parentDept!=null){
                    parentDept.getChildren().add(department);
                }
            }
        }
        return firstDepts;

    }
}
